/**
 * Created by xiaom on 2016/10/30.
 */
import React, {Component} from 'react';
import {
  Header,
  shouldUpdate,
  Input,
  Select,
  Label,
  Cell,
  Cells,
  CellHd,
  CellBd,
  CellsTitle
} from '../../components/index';
import PureRenderMixin from 'react-addons-pure-render-mixin';
import querystring from 'querystring';
import axios from 'axios';
import Toast from '../../components/Toast/index';
import Snackbar from 'material-ui/Snackbar';
import {red500} from 'material-ui/styles/colors';


export default class NetFix extends Component {

  constructor(props) {
    super(props);
    const _this = this;
    _this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(_this);
    _this.save = _this.save.bind(_this);
    _this.isUnmounted = false;
  }

  state = {
    select_status: 1,
    campus_list: [],
    operator_list: [],
    fault_type_list: [],
    building_list: [],
    openSnackbar: false,
    message: '',
    showLoading: false,
    showOk: false
  };

  shouldComponentUpdate(nextProps = {}, nextState = {}) {
    return shouldUpdate(this, nextProps, nextState);
  }

  save(event) {
    event.preventDefault();
    const _this = this;

    const FormBody = _this.refs.formBody;

    if (!(/^1\d{10}$/.test(FormBody.mobile.value))) {
      _this.SnackbarChange("手机号码有误，请重填");
      return false;
    }

    if (_this.state.select_status === 1) {
      if (FormBody.room_number.value.length !== 3) {
        console.log(FormBody.room_number.value.length);
        _this.SnackbarChange("房号不正确！");
        return false;
      }
    }

    _this.setState({showLoading: true});

    let params = querystring.stringify({
      open_id: '12345678912',
      name: FormBody.name.value.trim(),
      mobile: FormBody.mobile.value.trim(),
      building_id: FormBody.building_id.value.trim(),
      room_number: FormBody.room_number.value.trim(),
      operator_id: FormBody.operator_id.value.trim(),
      account: FormBody.account.value.trim(),
      fault_type_id: FormBody.fault_type_id.value.trim(),
      description: FormBody.description.value.trim()
    });

    axios.post('http://localhost/netmaker/backstage/index.php?g=api&m=WeChat&a=saveNet', params)
      .then(function (response) {
        if (response.data.code == 200) {
          _this.showOk();
          FormBody.reset();
          _this.setState({
            'select_status': 1
          });
        } else {
          _this.setState({showLoading: false});
          _this.SnackbarChange(response.data.message);
        }
      })
      .catch(function (error) {
        _this.SnackbarChange("网络错误！请稍后再试~");
        return false;
      });
  }

  selectStatusChange = (event) => {
    const _this = this;
    _this.setState({
      'select_status': event.target.value
    });
    _this.refs.formBody.room_number.value = '';
  };

  campusChange = (event)=> {
    this.getBuilding(event.target.value);
  };

  getBuilding = (campus_id)=> {
    const _this = this;
    if (campus_id > 0) {
      var params = querystring.stringify({
        campus_id: campus_id
      });

      axios.post('http://localhost/netmaker/backstage/index.php?g=api&m=WeChat&a=getBuilding', params)
        .then(function (response) {
          if (response.data.code == 200) {
            _this.setState({
              'building_list': response.data.data
            });
          } else {
            _this.setState({
              'building_list': []
            });
          }
        })
        .catch(function (error) {
          _this.SnackbarChange("网络错误！请稍后再试~");
          return false;
        });
    } else {
      _this.setState({
        'building_list': []
      });
    }
  };

  componentDidMount() {
    const _this = this;

    _this.getCampus();
    _this.getOperator();
    _this.getFaultType();

  }

  //获取校区
  getCampus() {
    const _this = this;
    axios.get('http://localhost/netmaker/backstage/index.php?g=api&m=WeChat&a=getCampus')
      .then(function (response) {
        if (response.data.code == 200) {
          if (!_this.isUnmounted) {
            _this.setState({campus_list: response.data.data});
          }
        } else {
          _this.SnackbarChange(response.data.message);
        }
      })
      .catch(function (error) {
        _this.SnackbarChange("网络错误！请稍后再试~");
        return false;
      });
  }

  //获取运营商
  getOperator() {
    const _this = this;
    axios.get('http://localhost/netmaker/backstage/index.php?g=api&m=WeChat&a=getOperator')
      .then(function (response) {
        if (response.data.code == 200) {
          if (!_this.isUnmounted) {
            _this.setState({operator_list: response.data.data});
          }
        } else {
          _this.SnackbarChange(response.data.message);
        }
      })
      .catch(function (error) {
        _this.SnackbarChange("网络错误！请稍后再试~");
        return false;
      });
  }

  getFaultType() {
    const _this = this;
    axios.get('http://localhost/netmaker/backstage/index.php?g=api&m=WeChat&a=getFaultType')
      .then(function (response) {
        if (response.data.code == 200) {
          if (!_this.isUnmounted) {
            _this.setState({fault_type_list: response.data.data});
          }
        } else {
          _this.SnackbarChange(response.data.message);
        }
      })
      .catch(function (error) {
        _this.SnackbarChange("网络错误！请稍后再试~");
        return false;
      });
  }

  SnackbarRequestClose = ()=> {
    this.setState({
      openSnackbar: false
    });
  };

  SnackbarChange = (message)=> {
    this.setState({
      openSnackbar: true,
      message: message
    });
  };

  showOk = ()=> {
    let _this = this;
    _this.setState({showOk: true, showLoading: false});
    setTimeout(()=> {
      _this.setState({showOk: false});
    }, 1500);
  };

  componentWillUnmount() {
    this.isUnmounted = true;
  }

  render() {
    const _this = this;
    const {showLoading, showOk, openSnackbar, message, campus_list, building_list, select_status, operator_list, fault_type_list} = _this.state;
    return (
      <div>
        <Header title="宽带报修"/>
        <Toast icon="weui-icon-success-no-circle" show={showOk} message="提交成功"/>
        <Toast message="正在提交" show={showLoading}/>
        <Snackbar
          open={openSnackbar}
          message={<p>{message}</p>}
          autoHideDuration={4000}
          onRequestClose={_this.SnackbarRequestClose}
          bodyStyle={{backgroundColor: red500}}
        />
        <form ref="formBody" onSubmit={_this.save} method="post">
          <Cells className="weui-cells_form">
            <Cell>
              <CellHd>
                <Label>姓名</Label>
              </CellHd>
              <CellBd>
                <Input type="text" name="name" placeholder="请输入姓名"/>
              </CellBd>
            </Cell>

            <Cell>
              <CellHd>
                <Label>手机</Label>
              </CellHd>
              <CellBd>
                <Input type="number" pattern="[0-9]*" name="mobile" placeholder="请输入手机号码"/>
              </CellBd>
            </Cell>

            <Cell className="weui-cell_select weui-cell_select-after">
              <CellHd>
                <Label>校区</Label>
              </CellHd>
              <CellBd>
                <Select name="campus_id" onChange={_this.campusChange}>
                  <option value="0">-- 请选择校区 --</option>
                  {
                    campus_list.map(function (object, index) {
                      return (
                        <option value={object.id}>{object.title}</option>
                      );
                    })
                  }
                </Select>
              </CellBd>
            </Cell>

            <Cell className="weui-cell_select weui-cell_select-after">
              <CellHd>
                <Label>区域</Label>
              </CellHd>
              <CellBd>
                <Select name="building_id">
                  <option value="0">-- 请选择区域 --</option>
                  {
                    building_list.map(function (object, index) {
                      return (
                        <option value={object.id}>{object.title}</option>
                      );
                    })
                  }
                </Select>
              </CellBd>
            </Cell>

            <Cell className="weui-cell_select weui-cell_select-after weui-cell_select-before">
              <CellHd>
                <Select name="select_status" onChange={_this.selectStatusChange}>
                  <option value="1">房号</option>
                  <option value="2">地点</option>
                </Select>
              </CellHd>
              <CellBd>
                {
                  select_status == 1 ? <Input type="number" name="room_number" placeholder="请输入房号，如：101"/> :
                    <Input type="text" name="room_number" placeholder="请输入地点名称"/>
                }
              </CellBd>
            </Cell>


            <Cell className="weui-cell_select weui-cell_select-after">
              <CellHd>
                <Label>运营商</Label>
              </CellHd>
              <CellBd>
                <Select name="operator_id">
                  <option value="0">-- 请选择运营商 --</option>
                  {
                    operator_list.map(function (object, index) {
                      return (
                        <option value={object.id}>{object.title}</option>
                      );
                    })
                  }
                </Select>
              </CellBd>
            </Cell>

            <Cell>
              <CellHd>
                <Label>宽带帐号</Label>
              </CellHd>
              <CellBd>
                <Input type="text" name="account" placeholder="请输入宽带帐号"/> </CellBd>
            </Cell>

          </Cells>

          <CellsTitle>故障描述</CellsTitle>

          <Cells className="weui-cells_form">

            <Cell className="weui-cell_select weui-cell_select-after">
              <CellHd>
                <Label>故障类型</Label>
              </CellHd>
              <CellBd>
                <Select name="fault_type_id">
                  <option value="0">-- 请选择故障类型 --</option>
                  {
                    fault_type_list.map(function (object, index) {
                      return (
                        <option value={object.id}>{object.title}</option>
                      );
                    })
                  }
                </Select>
              </CellBd>
            </Cell>

            <Cell>
              <CellBd>
                <textarea className="weui-textarea" name="description" placeholder="请输入故障描述" rows="4"></textarea>
              </CellBd>
            </Cell>
          </Cells>

          <div className="weui-btn-area">
            <button className="weui-btn weui-btn_primary" type="submit">确定</button>
          </div>
        </form>
      </div>
    );
  }
}
